package com.neusoft.databus.agent.bean;

import java.util.Map;

import org.springframework.util.StringUtils;

import com.neusoft.databus.common.constant.DatabusConstant;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class MetricConfig {
    // java script expression
    String expression = null;
    // the start index of bytes
    Integer start = 0;
    // the length of bytes to be read(maybe is unusable because of data type definition).
    Integer length = null;//2;
    // the start index of one byte if read by bit. {#MetricValueType.ANY}
    Integer bitStart = null;//0;
    // the length of bits to be read(maybe is unusable because it must be 1).
    Integer bitLength = null;//1;

    Integer precision = 2;

    /**
     * the mapping bean of metric extended configuration
     *
     * @param variable the variable name of metric
     * @param map metric extended configuration map object
     * @return
     */
    public static MetricConfig create(final Map<String, Object> map) {

        final MetricConfig config = new MetricConfig();
        if (null == map) {
            return config;
        }
        final String expression = (String) map.get(DatabusConstant.METRIC_CONFIG_FLAG_EXPRSSION);
        if (!StringUtils.isEmpty(expression)) {
            config.setExpression(expression);
        }

        if (map.containsKey(DatabusConstant.METRIC_CONFIG_FLAG_START)) {
            final int start = Integer.parseInt(String.valueOf(map.get(DatabusConstant.METRIC_CONFIG_FLAG_START)));
            if (start > -1) {
                config.setStart(start);
            }
        } else {
            config.setStart(0);
        }

        if (map.containsKey(DatabusConstant.METRIC_CONFIG_FLAG_LENGTH)) {
            final int length = Integer.parseInt(String.valueOf(map.get(DatabusConstant.METRIC_CONFIG_FLAG_LENGTH)));
            if (length > 0) {
                config.setLength(length);
            }
        }
        if (map.containsKey(DatabusConstant.METRIC_CONFIG_FLAG_BIT_START)) {
            final int bitStart =
                    Integer.parseInt(String.valueOf(map.get(DatabusConstant.METRIC_CONFIG_FLAG_BIT_START)));
            if (bitStart > -1) {
                config.setBitStart(bitStart);
            }
        }
        if (map.containsKey(DatabusConstant.METRIC_CONFIG_FLAG_BIT_LENGTH)) {
            final int bitLength =
                    Integer.parseInt(String.valueOf(map.get(DatabusConstant.METRIC_CONFIG_FLAG_BIT_LENGTH)));
            if (bitLength > 0) {
                config.setBitLength(bitLength);
            }
        }
        if (map.containsKey(DatabusConstant.METRIC_CONFIG_FLAG_PRECISION)) {
            final int precision =
                    Integer.parseInt(String.valueOf(map.get(DatabusConstant.METRIC_CONFIG_FLAG_PRECISION)));
            if (precision > 0) {
                config.setPrecision(precision);
            }
        }
        return config;
    }

}
